#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""工具栏组件"""

from PyQt5.QtWidgets import (
    QToolBar, QAction, QSeparator, QComboBox, QToolButton, QMenu, QWidget
)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QIcon, QFont, QFontDatabase


class MainToolBar(QToolBar):
    """主工具栏组件"""
    
    # 新建文件信号
    new_file = pyqtSignal()
    
    # 打开文件信号
    open_file = pyqtSignal()
    
    # 保存文件信号
    save_file = pyqtSignal()
    
    # 运行程序信号
    run_program = pyqtSignal()
    
    # 调试程序信号
    debug_program = pyqtSignal()
    
    # 撤销操作信号
    undo_action = pyqtSignal()
    
    # 重做操作信号
    redo_action = pyqtSignal()
    
    # 剪切操作信号
    cut_action = pyqtSignal()
    
    # 复制操作信号
    copy_action = pyqtSignal()
    
    # 粘贴操作信号
    paste_action = pyqtSignal()
    
    # 查找操作信号
    find_action = pyqtSignal()
    
    # 替换操作信号
    replace_action = pyqtSignal()
    
    # 字体大小变化信号
    font_size_changed = pyqtSignal(int)
    
    def __init__(self, parent=None):
        """初始化主工具栏"""
        super().__init__("工具栏", parent)
        
        # 设置工具栏属性
        self.setMovable(True)
        self.setFloatable(True)
        self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.setIconSize(32, 32)
        
        # 创建文件操作组
        self.create_file_actions()
        
        # 添加分隔符
        self.addSeparator()
        
        # 创建编辑操作组
        self.create_edit_actions()
        
        # 添加分隔符
        self.addSeparator()
        
        # 创建查看操作组
        self.create_view_actions()
        
        # 添加分隔符
        self.addSeparator()
        
        # 创建程序操作组
        self.create_program_actions()
        
        # 添加分隔符
        self.addSeparator()
        
        # 创建字体设置
        self.create_font_settings()
    
    def setIconSize(self, width, height):
        """设置图标大小"""
        super().setIconSize(self.parent().fontMetrics().size(Qt.TextSingleLine, "Abc").expandedTo(QSize(width, height)))
    
    def create_file_actions(self):
        """创建文件操作按钮"""
        # 新建文件按钮
        self.new_file_action = QAction("新建", self)
        self.new_file_action.setIcon(self.style().standardIcon(self.style().SP_FileIcon))
        self.new_file_action.setShortcut("Ctrl+N")
        self.new_file_action.setToolTip("新建文件 (Ctrl+N)")
        self.new_file_action.triggered.connect(self.new_file.emit)
        self.addAction(self.new_file_action)
        
        # 打开文件按钮
        self.open_file_action = QAction("打开", self)
        self.open_file_action.setIcon(self.style().standardIcon(self.style().SP_DialogOpenButton))
        self.open_file_action.setShortcut("Ctrl+O")
        self.open_file_action.setToolTip("打开文件 (Ctrl+O)")
        self.open_file_action.triggered.connect(self.open_file.emit)
        self.addAction(self.open_file_action)
        
        # 保存文件按钮
        self.save_file_action = QAction("保存", self)
        self.save_file_action.setIcon(self.style().standardIcon(self.style().SP_DialogSaveButton))
        self.save_file_action.setShortcut("Ctrl+S")
        self.save_file_action.setToolTip("保存文件 (Ctrl+S)")
        self.save_file_action.triggered.connect(self.save_file.emit)
        self.addAction(self.save_file_action)
    
    def create_edit_actions(self):
        """创建编辑操作按钮"""
        # 撤销操作按钮
        self.undo_action_btn = QAction("撤销", self)
        self.undo_action_btn.setIcon(self.style().standardIcon(self.style().SP_ArrowBack))
        self.undo_action_btn.setShortcut("Ctrl+Z")
        self.undo_action_btn.setToolTip("撤销操作 (Ctrl+Z)")
        self.undo_action_btn.triggered.connect(self.undo_action.emit)
        self.addAction(self.undo_action_btn)
        
        # 重做操作按钮
        self.redo_action_btn = QAction("重做", self)
        self.redo_action_btn.setIcon(self.style().standardIcon(self.style().SP_ArrowForward))
        self.redo_action_btn.setShortcut("Ctrl+Y")
        self.redo_action_btn.setToolTip("重做操作 (Ctrl+Y)")
        self.redo_action_btn.triggered.connect(self.redo_action.emit)
        self.addAction(self.redo_action_btn)
        
        # 添加分隔符
        self.addSeparator()
        
        # 剪切操作按钮
        self.cut_action_btn = QAction("剪切", self)
        self.cut_action_btn.setIcon(self.style().standardIcon(self.style().SP_CutIcon))
        self.cut_action_btn.setShortcut("Ctrl+X")
        self.cut_action_btn.setToolTip("剪切操作 (Ctrl+X)")
        self.cut_action_btn.triggered.connect(self.cut_action.emit)
        self.addAction(self.cut_action_btn)
        
        # 复制操作按钮
        self.copy_action_btn = QAction("复制", self)
        self.copy_action_btn.setIcon(self.style().standardIcon(self.style().SP_CopyIcon))
        self.copy_action_btn.setShortcut("Ctrl+C")
        self.copy_action_btn.setToolTip("复制操作 (Ctrl+C)")
        self.copy_action_btn.triggered.connect(self.copy_action.emit)
        self.addAction(self.copy_action_btn)
        
        # 粘贴操作按钮
        self.paste_action_btn = QAction("粘贴", self)
        self.paste_action_btn.setIcon(self.style().standardIcon(self.style().SP_PasteIcon))
        self.paste_action_btn.setShortcut("Ctrl+V")
        self.paste_action_btn.setToolTip("粘贴操作 (Ctrl+V)")
        self.paste_action_btn.triggered.connect(self.paste_action.emit)
        self.addAction(self.paste_action_btn)
        
        # 添加分隔符
        self.addSeparator()
        
        # 查找操作按钮
        self.find_action_btn = QAction("查找", self)
        self.find_action_btn.setIcon(self.style().standardIcon(self.style().SP_FileDialogContentsView))
        self.find_action_btn.setShortcut("Ctrl+F")
        self.find_action_btn.setToolTip("查找 (Ctrl+F)")
        self.find_action_btn.triggered.connect(self.find_action.emit)
        self.addAction(self.find_action_btn)
        
        # 替换操作按钮
        self.replace_action_btn = QAction("替换", self)
        self.replace_action_btn.setIcon(self.style().standardIcon(self.style().SP_FileDialogDetailedView))
        self.replace_action_btn.setShortcut("Ctrl+H")
        self.replace_action_btn.setToolTip("替换 (Ctrl+H)")
        self.replace_action_btn.triggered.connect(self.replace_action.emit)
        self.addAction(self.replace_action_btn)
    
    def create_view_actions(self):
        """创建查看操作按钮"""
        # 设计器/代码视图切换按钮
        self.view_mode_btn = QToolButton()
        self.view_mode_btn.setText("视图")
        self.view_mode_btn.setToolTip("切换视图模式")
        self.view_mode_btn.setPopupMode(QToolButton.MenuButtonPopup)
        
        # 创建视图模式菜单
        view_mode_menu = QMenu(self.view_mode_btn)
        
        # 代码视图动作
        self.code_view_action = QAction("代码视图", self)
        self.code_view_action.setCheckable(True)
        self.code_view_action.setChecked(True)
        view_mode_menu.addAction(self.code_view_action)
        
        # 设计器视图动作
        self.designer_view_action = QAction("设计器视图", self)
        self.designer_view_action.setCheckable(True)
        view_mode_menu.addAction(self.designer_view_action)
        
        # 分割视图动作
        self.split_view_action = QAction("分割视图", self)
        self.split_view_action.setCheckable(True)
        view_mode_menu.addAction(self.split_view_action)
        
        # 添加到按钮
        self.view_mode_btn.setMenu(view_mode_menu)
        
        # 添加到工具栏
        self.addWidget(self.view_mode_btn)
        
        # 创建按钮组，确保只有一个按钮被选中
        from PyQt5.QtWidgets import QActionGroup
        view_mode_group = QActionGroup(self)
        view_mode_group.addAction(self.code_view_action)
        view_mode_group.addAction(self.designer_view_action)
        view_mode_group.addAction(self.split_view_action)
        view_mode_group.setExclusive(True)
    
    def create_program_actions(self):
        """创建程序操作按钮"""
        # 运行程序按钮
        self.run_program_action = QAction("运行", self)
        self.run_program_action.setIcon(self.style().standardIcon(self.style().SP_MediaPlay))
        self.run_program_action.setShortcut("F5")
        self.run_program_action.setToolTip("运行程序 (F5)")
        self.run_program_action.triggered.connect(self.run_program.emit)
        self.addAction(self.run_program_action)
        
        # 调试程序按钮
        self.debug_program_action = QAction("调试", self)
        self.debug_program_action.setIcon(self.style().standardIcon(self.style().SP_MediaSkipForward))
        self.debug_program_action.setShortcut("F9")
        self.debug_program_action.setToolTip("调试程序 (F9)")
        self.debug_program_action.triggered.connect(self.debug_program.emit)
        self.addAction(self.debug_program_action)
    
    def create_font_settings(self):
        """创建字体设置"""
        # 字体大小下拉框
        self.font_size_combo = QComboBox()
        self.font_size_combo.setToolTip("选择字体大小")
        self.font_size_combo.setMinimumWidth(60)
        
        # 添加常用字体大小
        for size in [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32]:
            self.font_size_combo.addItem(f"{size}", size)
        
        # 设置默认字体大小
        default_index = self.font_size_combo.findData(12)
        if default_index >= 0:
            self.font_size_combo.setCurrentIndex(default_index)
        
        # 连接信号
        self.font_size_combo.currentIndexChanged.connect(self.on_font_size_changed)
        
        # 添加到工具栏
        self.addWidget(self.font_size_combo)
    
    def on_font_size_changed(self, index):
        """处理字体大小变化"""
        # 获取选中的字体大小
        font_size = self.font_size_combo.itemData(index)
        
        # 发送字体大小变化信号
        self.font_size_changed.emit(font_size)
    
    def update_action_states(self, **kwargs):
        """更新操作按钮的状态"""
        # 更新文件操作按钮状态
        if "can_save" in kwargs:
            self.save_file_action.setEnabled(kwargs["can_save"])
        
        # 更新编辑操作按钮状态
        if "can_undo" in kwargs:
            self.undo_action_btn.setEnabled(kwargs["can_undo"])
        
        if "can_redo" in kwargs:
            self.redo_action_btn.setEnabled(kwargs["can_redo"])
        
        if "has_selection" in kwargs:
            self.cut_action_btn.setEnabled(kwargs["has_selection"])
            self.copy_action_btn.setEnabled(kwargs["has_selection"])
        
        # 更新程序操作按钮状态
        if "can_run" in kwargs:
            self.run_program_action.setEnabled(kwargs["can_run"])
            self.debug_program_action.setEnabled(kwargs["can_run"])
    
    def set_view_mode(self, mode):
        """设置视图模式
        mode: "code", "designer", "split"
        """
        self.code_view_action.setChecked(mode == "code")
        self.designer_view_action.setChecked(mode == "designer")
        self.split_view_action.setChecked(mode == "split")
    
    def get_view_mode(self):
        """获取当前视图模式"""
        if self.code_view_action.isChecked():
            return "code"
        elif self.designer_view_action.isChecked():
            return "designer"
        elif self.split_view_action.isChecked():
            return "split"
        return "code"


class StatusBarWidget(QWidget):
    """状态栏组件"""
    
    def __init__(self, parent=None):
        """初始化状态栏"""
        super().__init__(parent)
        
        # 创建布局
        from PyQt5.QtWidgets import QHBoxLayout
        self.setLayout(QHBoxLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().setSpacing(10)
        
        # 创建文件类型标签
        from PyQt5.QtWidgets import QLabel
        self.file_type_label = QLabel("无文件")
        self.file_type_label.setMinimumWidth(80)
        self.file_type_label.setAlignment(Qt.AlignCenter)
        self.layout().addWidget(self.file_type_label)
        
        # 创建行号标签
        self.line_label = QLabel("行: 0")
        self.line_label.setMinimumWidth(60)
        self.line_label.setAlignment(Qt.AlignCenter)
        self.layout().addWidget(self.line_label)
        
        # 创建列号标签
        self.column_label = QLabel("列: 0")
        self.column_label.setMinimumWidth(60)
        self.column_label.setAlignment(Qt.AlignCenter)
        self.layout().addWidget(self.column_label)
        
        # 添加弹性空间
        from PyQt5.QtWidgets import QSpacerItem, QSizePolicy
        spacer = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.layout().addItem(spacer)
        
        # 创建编码标签
        self.encoding_label = QLabel("UTF-8")
        self.encoding_label.setMinimumWidth(60)
        self.encoding_label.setAlignment(Qt.AlignCenter)
        self.layout().addWidget(self.encoding_label)
        
        # 创建行尾标签
        self.eol_label = QLabel("LF")
        self.eol_label.setMinimumWidth(40)
        self.eol_label.setAlignment(Qt.AlignCenter)
        self.layout().addWidget(self.eol_label)
    
    def update_position_info(self, line, column):
        """更新位置信息"""
        self.line_label.setText(f"行: {line}")
        self.column_label.setText(f"列: {column}")
    
    def update_file_info(self, file_path=None):
        """更新文件信息"""
        if file_path:
            import os
            # 获取文件扩展名
            _, ext = os.path.splitext(file_path)
            ext = ext.upper() if ext else "文本"
            
            # 更新文件类型标签
            self.file_type_label.setText(ext)
        else:
            # 无文件打开
            self.file_type_label.setText("无文件")
    
    def set_encoding(self, encoding):
        """设置编码信息"""
        self.encoding_label.setText(encoding)
    
    def set_eol(self, eol):
        """设置行尾信息"""
        self.eol_label.setText(eol)